// This is the main DLL file.

#include "stdafx.h"

#include "HidDevice.h"
#include "HidDevices.h"

using namespace HidLib;
using namespace System::Threading;

HidDeviceEventMonitor::HidDeviceEventMonitor(HidDevice^ Device)
{
	_Device = Device;
	_PollingFrequency = 500;
}

void HidDeviceEventMonitor::Init()
{
	EventMonitorDelegate^ EventMonitor = gcnew EventMonitorDelegate(this, &HidDeviceEventMonitor::DeviceEventMonitor);

	EventMonitor->BeginInvoke(gcnew AsyncCallback(&HidDeviceEventMonitor::DisposeDeviceEventMonitor), EventMonitor);
}

void HidDeviceEventMonitor::DisposeDeviceEventMonitor(IAsyncResult^ Ar)
{
	((EventMonitorDelegate^)Ar->AsyncState)->EndInvoke(Ar);
}

void HidDeviceEventMonitor::DeviceEventMonitor(void)
{
	_Connected = HidDevices::IsConnected(_Device->DevicePath);

	if(_Connected != _DeviceWasConnected)
	{
		if(_Connected)
		{
			OnInsert();
		}
		else
		{
			OnRemove();
		}
		_DeviceWasConnected = _Connected;
	}
	Thread::Sleep(PollingFrequency);

	if(_Enabled)
		Init();
}